import React, { useEffect, useState } from 'react'
import { Button, Empty, message, Modal, Space, Spin } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import {
  exportProductFabricConfig,
  getProductClassConfigByType,
  getProductFabricPageList,
  productFabricConfigimportExcel,
  productFabricConfigUpdateStatus,
} from '@/api/goods'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import { ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { useNavigate } from 'react-router-dom'
import { IMPORT_FILE_ENUM, STATUSBANDOPTIONS } from '@/constant'
import { ImportOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons'
import { exportNotification, importNotification } from '@/utils/util'
import ImportFileModal from '@/components/ImportFileModal'
import { onValuesChange } from '@/utils/onValuesChange'
import PermissionButton from '@/components/PermissionButton'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
import useModal from '@/hooks/useModal'
import { EditFormInline, EditFormVertical } from '@/components/QsfCustomForm'
import './index.less'
import useSearchFabric from '@/hooks/useSearchFabric'
import useSearchFabricType from '@/hooks/useSearchFabricType'
import { useAppSelector } from '@/store/hooks'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import { editSupplierGreyFabric, productFabricConfigCreate } from '@/api/fabric'
import { useFormAdd } from './useForm'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [form] = useForm()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [FormUpload] = useForm()
  const { FabricOption, handleSearchFabric } = useSearchFabric('fabricCode')
  const { FabricTypeOptions, handleSearchFabricType } = useSearchFabricType()
  const { SupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [exportLoading, setexportLoading] = useState(false)
  const [spinning, setspinning] = useState<boolean>(false)
  const ProDevSeason = useGetProDevSeason('seasonName')
  const { tableProps, params, search, reset } = useGetTableData<ITableData>(getProductFabricPageList, {
    form: form,
    defaultFieldsParams: {
      status: 1,
    },
    immediatelySend: false,
  })
  const addModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      search(params)
    },
  })
  useEffect(() => {
    getProductClassConfig()
    search({ ...params, status: 1 })
  }, [])
  const selectRows = (keys: React.Key[]) => {
    setselectedRowKeys(keys)
  }
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    const res = await productFabricConfigimportExcel<{ linkUrl: string }>(file).finally(() => {
      setexportLoading(false)
      FormUpload.resetFields()
    })
    if (res.code === 200) {
      importNotification(res?.data?.linkUrl)
      search(params)
      onUploadFileCancel()
    }
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  return (
    <PageContainer className="goods_fabric_page">
      <SearchForm
        params={params}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['searchName'], form)}
        form={form}
        searchConfig={[
          { label: '面料', name: 'searchName', type: 'Input', placeholder: '面料编码/面料名称' },
          { label: '开发季', name: 'devSeason', type: 'Select', option: ProDevSeason },
          {
            label: '大类',
            name: 'bigClassIds',
            type: 'Select',
            option: classBig,
            config: {
              showSearch: true,
              optionFilterProp: 'label',
              mode: 'multiple',
              maxTagCount: 'responsive',
            },
          },
          {
            label: '是否集约',
            name: 'intensiveStatus',
            type: 'Select',
            option: [
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ],
          },
          { label: '状态', name: 'status', type: 'Select', option: STATUSBANDOPTIONS },
        ]}
        onFinish={(vals: any) => {
          setselectedRowKeys([])
          search(vals)
        }}
        onReset={() => {
          setselectedRowKeys([])
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="batchAddFabric"
                type="primary"
                onClick={() => {
                  addModal.form.setFieldsValue({ devSeason: ProDevSeason[0].value, intensiveStatus: 1 })
                  addModal.openModal()
                }}
                icon={<PlusOutlined />}
              >
                新建面料
              </PermissionButton>
              <PermissionButton
                permission="batchAddFabric"
                type="primary"
                onClick={() => {
                  setisUploadFileShow(true)
                }}
                icon={<ImportOutlined />}
              >
                批量新建面料
              </PermissionButton>
              <PermissionButton
                permission="onFabric"
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const res = await productFabricConfigUpdateStatus({ ids: selectedRowKeys, status: 1 })
                  if (res.code === 200) {
                    message.success('操作成功')
                    setselectedRowKeys([])
                    search(params)
                  }
                }}
              >
                启用面料
              </PermissionButton>
              <PermissionButton
                permission="offFabric"
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const res = await productFabricConfigUpdateStatus({ ids: selectedRowKeys, status: 0 })
                  if (res.code === 200) {
                    message.success('操作成功')
                    setselectedRowKeys([])
                    search(params)
                  }
                }}
              >
                停用面料
              </PermissionButton>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="exportProductFabricConfig"
                onClick={async () => {
                  const paramsData: Record<string, any> = {}
                  if (selectedRowKeys.length > 0) {
                    paramsData.fabricIds = selectedRowKeys
                  } else {
                    Object.assign(paramsData, params)
                  }
                  setexportLoading(true)
                  setspinning(true)
                  const res = await exportProductFabricConfig(paramsData)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setexportLoading(false)
                      setselectedRowKeys([])
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
                icon={<UploadOutlined />}
                loading={exportLoading}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        columns={useIndexColumns({ navigate })}
        {...tableProps}
        rowKey={(rows) => rows.fabricId}
        isScrollY
      />
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={IMPORT_FILE_ENUM.GOODS_FABRIC_IMPORT}
      ></ImportFileModal>
      <Modal
        width={800}
        title="新建面料"
        open={addModal.open}
        maskClosable
        onCancel={addModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={addModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={addModal.confirmLoading}
                onClick={() => {
                  addModal.handleSubmit((vals) =>
                    productFabricConfigCreate({
                      ...vals,
                      devSeasonId: ProDevSeason?.find((item) => item.value == vals.devSeason)?.seasonId,
                    }),
                  )
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div>
          <EditFormInline
            grid={{ xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 }}
            editConfig={useFormAdd({
              classBig,
              DICTDATA,
              SupplierOption,
              handleSearchSupplier,
              ProDevSeason,
              FabricOption,
              handleSearchFabric,
              form: addModal.form,
              FabricTypeOptions,
              handleSearchFabricType,
            })}
            form={addModal.form}
          />
        </div>
      </Modal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
